package org.devgframwork.flowsystem.config.interceptors;

import org.devgframwork.flowsystem.api.admin.user.service.UserService;
import org.devgframwork.platform.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author duheng
 * @Date 2021/11/13 17:00
 */
@Slf4j
@Component
public class AdminApiInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        String userId = request.getHeader("userId");
        log.info("userId:{},token:{}", userId, token);
        if (CommonUtil.isNullOrEmpty(token) || CommonUtil.isNullOrEmpty(userId)) {
            response.sendRedirect(request.getContextPath() + "/error/401");
            return false;
        }
        String tokenKey = UserService.prefixKey + userId;
        String tokenValue = stringRedisTemplate.opsForValue().get(tokenKey);
        if (CommonUtil.isNullOrEmpty(tokenValue) || !CommonUtil.equals(token, tokenValue)) {
            log.info("userId:{} token expire", userId);
            response.sendRedirect(request.getContextPath() + "/error/401");
            return false;
        }
        return true;
    }
}
